C#_c#数字图像处理的3种方法示例分享,本文主要通过彩色图象灰度化
复制代码 代码如下:
newbitmap.UnlockBits(bmpdata);
System.Drawing.Imaging.BitmapData bmpdata = newbitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, newbitmap.PixelFormat);
LockBits方法和UnlockBits方法,分别锁定和解锁系统内存中的位图像素。
double colortemp = 0;
}
PixelFormat属性,返回图像的像素格式。
{
ptr += bmpdata.Stride - bmpdata.Width * 3;
Palette属性,获取或折纸图像所使用的颜色调色板。
{byte* ptr = (byte*)(bmpdata.Scan0);
unsafe
System.Drawing.Imaging.BitmapData bmpdata = newbitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, newbitmap.PixelFormat);
ptr[0] = ptr[1] = ptr[2] = temp;
pictureBox1.Image = newbitmap.Clone() as Image;
temp = (byte)(0.299 * ptr[2] + 0.587 * ptr[1] + 0.114 * ptr[0]);
PixelFormat属性,数据的实际像素格式。
使用的是GDI+中的Bitmap.GetPixel和Bitmap.SetPixel方法。
{colortemp = rgbvalues[i + 2] * 0.299 + rgbvalues[i + 1] * 0.587 + rgbvalues[i] * 0.114;
pictureBox1.Image = newbitmap.Clone() as Image;
Bitmap只要用于处理由像素数据定义的图像的对象,主要方法和属性如下:
{}
for (int y = 0; y < bmpdata.Height; y++)
指针法
for (int y = 0; y < newbitmap.Height; y++)Height属性,被锁定位图的高度。
if (bitmap != null)ret = (int)(pixel.R * 0.299 + pixel.G * 0.587 + pixel.B * 0.114);
newbitmap = bitmap.Clone() as Bitmap;
byte[] rgbvalues = new byte[bytes];
观察发现绿色所占比重最大,所以转换时直接使用G值作为转换结果:
for (int x = 0; x < bmpdata.Width; x++)图像处理的3种方法分别是:提取像素法、内存法和指针法,它们各自有各自的特点。
Stride属性,步幅,也称扫描宽度。
if (bitmap != null)
Rectangle rect = new Rectangle(0, 0, newbitmap.Width, newbitmap.Height);
}
内存法是把图像数据直接复制到内存中,这样程序的运行速度就能大大提高了。
{newbitmap = bitmap.Clone() as Bitmap;
System.Runtime.InteropServices.Marshal.Copy(rgbvalues, 0, ptr, bytes);
Width属性,被锁定位图的宽度。
Gray(I,j)为转换后的灰度图像在(I,j)点出的灰度值。由于人眼对颜色的感应不同,有了下面的转换公式:
{newbitmap.SetPixel(x, y, Color.FromArgb(ret, ret, ret));
{
newbitmap = bitmap.Clone() as Bitmap;
byte temp;
newbitmap.UnlockBits(bmpdata);
内存法
{pixel = newbitmap.GetPixel(x, y);
本文主要通过彩色图象灰度化来介绍C#处理数字图像的3种方法,Bitmap类、BitmapData类和Graphics类是C#处理图像的的3个重要的类。
pictureBox1.Image = newbitmap.Clone() as Image;ptr += 3;
复制代码 代码如下:
}Rectangle rect = new Rectangle(0, 0, newbitmap.Width, newbitmap.Height);
彩色图象灰度化
IntPtr ptr = bmpdata.Scan0;{
Scan0属性,被锁定数组的首字节地址。
int ret;
提取像素法
for (int x = 0; x < newbitmap.Width; x++)System.Runtime.InteropServices.Marshal.Copy(ptr, rgbvalues, 0, bytes);
Color pixel;
Height属性和Width属性,返回图像的高度和宽度。
rgbvalues[i] = rgbvalues[i + 1] = rgbvalues[i + 2] = (byte)colortemp;复制代码 代码如下:
}}
}
这个方法和内存法相似,开始都是通过LockBits方法来获取位图的首地址,这个方法更简洁,直接用指针进行位图操作。所以对内存的操作需要在unsafe下进行操作。
BitmapData对象指定了位图的属性:
}int bytes = newbitmap.Width * newbitmap.Height * 3;
for (int i = 0; i < rgbvalues.Length; i += 3)
24位彩色图象每个像素用3个字节表示,每个字节对应着R、G、B分量的亮度(红、绿、蓝)。当3个分量不想同时表现为灰度图像。下面有三种转换公式:
}if (bitmap != null)
GetPixel方法和SetPixel方法,获取和设置一个图像的指定像素的颜色。
本站内容来源于网络,如有侵权请与我们联系,我们会及时删除,我们深感抱歉!
注:本站所有信息仅供用于网络技术学习参考,学习中请遵循相关法律法规!
本文地址: https://v30.fanwenzhu.com/jiaob/c/6389.shtml
